<script>
import { ref, reactive, onMounted } from 'vue'
import { page, findById, deleteById, save } from '@/api/phyExam'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, FirstAidKit, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue'
import { getCareGiverList } from '@/api/caregiver'
import { getElderList } from '@/api/elderInfo'

export default {
  setup() {
    // 表格数据
    const tableData = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const formType = ref('add') // add or edit
    const careGiverList=ref([])
    const elderList=ref([])
    // 分页参数
    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })
    
    // 查询参数
    const queryParams = reactive({
      name: '',
    })
    
    // 表单数据
    const form = reactive({
      checkId: null,
      elderlyId: null,
      caregiverId: null,
      checkTime: '',
      height: null,
      weight: null,
      systolicPressure: null,
      diastolicPressure: null,
      heartRate: null,
      temperature: null,
      bloodSugar: null,
      healthStatus: '',
      checkResult: 0,
      suggestion: ''
    })
    
    // 表单验证规则
    const rules = reactive({
      elderlyId: [{ required: true, message: '请选择老人', trigger: 'blur' }],
      checkTime: [{ required: true, message: '请选择体检时间', trigger: 'blur' }],
      systolicPressure: [{ required: true, message: '请输入收缩压', trigger: 'blur' }],
      diastolicPressure: [{ required: true, message: '请输入舒张压', trigger: 'blur' }]
    })
    
    // 获取体检记录列表
    const getList = async () => {
      loading.value = true
      try {
        const params = {
          pageNo: pagination.current,
          pageSize: pagination.size,
          ...queryParams
        }
        const res = await page(params)
        tableData.value = res.data.records
        console.log("tableData.value:"+tableData)
        console.log(tableData.value)
        pagination.total = res.data.total
      } catch (error) {
        console.error(error)
      } finally {
        loading.value = false
      }
    }
    
    // 分页变化
    const handleSizeChange = (val) => {
      pagination.size = val
      getList()
    }
    
    const handleCurrentChange = (val) => {
      pagination.current = val
      getList()
    }
    
    // 重置查询
    const resetQuery = () => {
      queryParams.elderlyName = ''
      queryParams.checkResult = ''
      queryParams.startTime = ''
      queryParams.endTime = ''
      getList()
    }
    
    // 打开新增对话框
    const handleAdd = () => {
      dialogTitle.value = '新增体检记录'
      formType.value = 'add'
      resetForm()
      dialogVisible.value = true
    }
    
    // 打开编辑对话框
    const handleEdit = async (row) => {
      dialogTitle.value = '编辑体检记录'
      formType.value = 'edit'
      try {
        const res = await findById(row.checkId)
        Object.assign(form, res.data)
        dialogVisible.value = true
      } catch (error) {
        console.error(error)
      }
    }
    
    // 查看详情
    const handleDetail = async (row) => {
      dialogTitle.value = '体检记录详情'
      formType.value = 'view'
      try {
        const res = await findById(row.checkId)
        Object.assign(form, res.data)
        dialogVisible.value = true
      } catch (error) {
        console.error(error)
      }
    }
    
    // 删除记录
    const handleDelete = (row) => {
      ElMessageBox.confirm('确认删除该体检记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteById(row.checkId)
        ElMessage.success('删除成功')
        getList()
      }).catch(() => {})
    }
    
    // 提交表单
    const submitForm = async () => {
      try {
        await save(form)
        ElMessage.success('操作成功')
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error(error)
      }
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        checkId: null,
        elderlyId: null,
        caregiverId: null,
        checkTime: '',
        height: null,
        weight: null,
        systolicPressure: null,
        diastolicPressure: null,
        heartRate: null,
        temperature: null,
        bloodSugar: null,
        healthStatus: '',
        checkResult: 0,
        suggestion: ''
      })
    }
    
    // 初始化加载数据
    // 通用的数据加载函数
const fetchData = async (apiFn, refValue) => {
  try {
    const res = await apiFn()
    refValue.value = res.data
    console.log()
    return true
  } catch (error) {
    console.error('数据加载失败:', error)
     ElMessage.error(`${apiFn.name} 数据加载失败`)
    return false
  }
}

onMounted(async () => {
  // 并行执行所有请求
  const results = await Promise.allSettled([
    fetchData(getCareGiverList, careGiverList),
    fetchData(getElderList, elderList)
  ])
  
  // 检查是否全部成功
  const allSuccess = results.every(result => result.value)
  if (allSuccess) {
    getList()
  }
})
    
    return {
      tableData,
      loading,
      dialogVisible,
      dialogTitle,
      formType,
      pagination,
      queryParams,
      form,
      rules,
      careGiverList,
      elderList,
      getList,
      handleSizeChange,
      handleCurrentChange,
      resetQuery,
      handleAdd,
      handleEdit,
      handleDetail,
      handleDelete,
      submitForm,
      resetForm,
      icons: {
        Document,
        FirstAidKit,
        Edit,
        Delete,
        Search,
        Refresh
      }
    }
  }
}
</script>

<template>
    <h1>你好</h1>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-card shadow="never" class="search-card">
  <el-form :inline="true" :model="queryParams" class="search-form">
    <el-form-item label="老人姓名">
      <el-input
        v-model="queryParams.elderlyName"
        placeholder="请输入老人姓名"
        clearable
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" :icon="icons.Search" @click="getList">查询</el-button>
      <el-button :icon="icons.Refresh" @click="resetQuery">重置</el-button>
    </el-form-item>
    <el-form-item class="add-button">
      <el-button type="primary" :icon="icons.Document" @click="handleAdd">新增体检</el-button>
    </el-form-item>
  </el-form>
</el-card>


    <!-- 数据表格 -->
    <el-card shadow="never">
      <el-table
  v-loading="loading"
  :data="tableData"
  border
  stripe
  style="width: 100%"
>
  <el-table-column prop="checkId" label="记录ID" width="80" align="center" fixed/>
  <el-table-column prop="elderInfo.name" label="老人姓名" width="120" align="center" />
  <el-table-column prop="checkTime" label="体检时间" width="160" align="center">
    <template #default="{row}">
      {{ row.checkTime ? new Date(row.checkTime).toLocaleString() : '-' }}
    </template>
  </el-table-column>
  
  <!-- 身体指标数据 -->
  <el-table-column prop="height" label="身高(cm)" width="100" align="center" />
  <el-table-column prop="weight" label="体重(kg)" width="100" align="center" />
  <el-table-column label="血压(mmHg)" width="140" align="center">
    <template #default="{row}">
      {{ row.systolicPressure }}/{{ row.diastolicPressure }}
    </template>
  </el-table-column>
  <el-table-column prop="heartRate" label="心率(次/分)" width="110" align="center" />
  <el-table-column prop="temperature" label="体温(°C)" width="100" align="center" />
  <el-table-column prop="bloodSugar" label="血糖(mmol/L)" width="120" align="center" />
  <!-- 体检结果 -->
  <el-table-column label="体检结果" width="100" align="center">
    <template #default="{row}">
      <el-tag :type="row.checkResult === 0 ? 'success' : 'danger'">
        {{ row.checkResult === 0 ? '正常' : '异常' }}
      </el-tag>
    </template>
  </el-table-column>
  
  <!-- 建议（使用tooltip显示完整内容） -->
  <el-table-column prop="suggestion" label="建议" width="150" align="center" show-overflow-tooltip />
  
  <!-- 操作列 -->
  <el-table-column label="操作" width="252" align="center" fixed="right">
    <template #default="{row}">
      <el-button type="primary" size="small" :icon="icons.FirstAidKit" @click="handleDetail(row)">详情</el-button>
      <el-button type="warning" size="small" :icon="icons.Edit" @click="handleEdit(row)">编辑</el-button>
      <el-button type="danger" size="small" :icon="icons.Delete" @click="handleDelete(row)">删除</el-button>
    </template>
  </el-table-column>
</el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
  <el-form-item label="老人" prop="elderlyId">
    <el-select
      v-model="form.elderlyId"
      placeholder="请选择老人"
      style="width: 100%"
      :disabled="formType === 'view'"
    >
      <el-option
        v-for="elder in elderList"
        :key="elder.elderId"
        :label="elder.value"
        :value="elder.elderId"
      />
    </el-select>
  </el-form-item>
</el-col>

<el-col :span="12">
  <el-form-item label="护工" prop="caregiverId">
    <el-select
      v-model="form.caregiverId"
      placeholder="请选择护工"
      style="width: 100%"
      :disabled="formType === 'view'"
    >
      <el-option
        v-for="caregiver in careGiverList"
        :key="caregiver.careGiverId"
        :label="caregiver.value"
        :value="caregiver.careGiverId"
      />
    </el-select>
  </el-form-item>
</el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="体检时间" prop="checkTime">
              <el-date-picker
                v-model="form.checkTime"
                type="datetime"
                placeholder="选择体检时间"
                style="width: 100%"
                :disabled="formType === 'view'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体检结果" prop="checkResult">
              <el-select
                v-model="form.checkResult"
                placeholder="请选择体检结果"
                style="width: 100%"
                :disabled="formType === 'view'"
              >
                <el-option label="正常" :value="0" />
                <el-option label="异常" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身高(cm)" prop="height">
              <el-input-number
                v-model="form.height"
                :min="0"
                :max="250"
                :precision="1"
                :disabled="formType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重(kg)" prop="weight">
              <el-input-number
                v-model="form.weight"
                :min="0"
                :max="200"
                :precision="1"
                :disabled="formType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收缩压(mmHg)" prop="systolicPressure">
              <el-input-number
                v-model="form.systolicPressure"
                :min="0"
                :max="300"
                :disabled="formType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="舒张压(mmHg)" prop="diastolicPressure">
              <el-input-number
                v-model="form.diastolicPressure"
                :min="0"
                :max="200"
                :disabled="formType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="心率(次/分)" prop="heartRate">
              <el-input-number
                v-model="form.heartRate"
                :min="0"
                :max="200"
                :disabled="formType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体温(°C)" prop="temperature">
              <el-input-number
                v-model="form.temperature"
                :min="30"
                :max="45"
                :step="0.1"
                :precision="1"
                :disabled="formType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="血糖(mmol/L)" prop="bloodSugar">
              <el-input-number
                v-model="form.bloodSugar"
                :min="0"
                :max="50"
                :step="0.1"
                :precision="1"
                :disabled="formType === 'view'"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="健康状况" prop="healthStatus">
          <el-input
            v-model="form.healthStatus"
            type="textarea"
            :rows="2"
            placeholder="请输入健康状况描述"
            :disabled="formType === 'view'"
          />
        </el-form-item>
        
        <el-form-item label="建议" prop="suggestion">
          <el-input
            v-model="form.suggestion"
            type="textarea"
            :rows="2"
            placeholder="请输入建议"
            :disabled="formType === 'view'"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            v-if="formType !== 'view'"
            type="primary"
            @click="submitForm"
          >
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.search-card {
  margin-bottom: 20px;
}
.toolbar-card {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.date-separator {
  margin: 0 10px;
  color: #606266;
}
.search-card .search-form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-card .add-button {
  margin-left: auto;
}
</style>